package com.vcredit.creditcat.web.app;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.vcredit.creditcat.dto.speedloan.*;
import com.vcredit.creditcat.vo.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.vcredit.creditcat.api.IAppTokenManager;
import com.vcredit.creditcat.api.ICustAccountManage;
import com.vcredit.creditcat.api.ICustManager;
import com.vcredit.creditcat.api.ISpeedloanManager;
import com.vcredit.creditcat.dto.speedloan.SpeedIndexV3Dto;
import com.vcredit.creditcat.dto.speedloan.SpeedloanIndexDto;
import com.vcredit.creditcat.dto.speedloan.SpeedloanPrecheckDto;
import com.vcredit.creditcat.dto.speedloan.SpeedloanPrecheckItemDto;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 快速贷款
 * 
 * @author zhaoqi01
 */
@RestController
@RequestMapping("speedloan")
public class SpeedloanController extends BaseCreditCatController {

	private static final Logger LOG = LoggerFactory.getLogger(SpeedloanController.class);

	@Reference(version = "1.0")
	private ISpeedloanManager speedloanManager;

	@Reference(version = "1.0")
	private IAppTokenManager appTokenService;

	@Reference(version = "1.0")
	private ICustManager custManager;
	@Reference(version = "1.0")
	private ICustAccountManage custAccountManage;
	/**
	 * 快速贷款预检（查询列表或单个）
	 * 
	 * @author zhaoqi01
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Log
	@RequestMapping("index")
	public SpeedloanPrecheckDto precheckList(HttpServletRequest request) throws Exception {
		Cust cust = null;
		String accessToken = request.getHeader("accessToken");
		String appDesc = request.getHeader("appDesc");
		Long custId = null;
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			cust = custManager.findById(custId);
		}
		cust = cust == null ? new Cust() : cust;
		BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
		String body = IOUtils.read(reader);

		LOG.info("------------旧快贷首页 appDesc：" + appDesc + ", body：" + body);

		if (body.indexOf("creditcat;1.4.2") != -1 && body.indexOf("android") != -1) { // 兼容
			Map<String, String> map = new HashMap<String, String>();
			map.put("appDesc", body);
			body = JacksonUtil.Obj2Json(map);
		} else if (body.indexOf("appDesc") == -1) {
			body = body.replace("}", ",\"appDesc\":\"" + appDesc + "\"}");
		}

		SpeedloanPrecheckDto result = speedloanManager.precheckList(cust, body);
		return result;
	}

	@Log
	@RequestMapping("index/v2")
	public SpeedloanIndexDto index(@RequestBody Map<String, Object> params, HttpServletRequest request) throws Exception {
		Cust cust = null;
		String accessToken = request.getHeader("accessToken");
		String appDesc = request.getHeader("appDesc");
		Long custId = null;
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			cust = custManager.findById(custId);
		}
		cust = cust == null ? new Cust() : cust;

		int pageIndex = 0;
		int pageSize = 10;
		Long productId = (params.get("productId") == null || StringUtils.isBlank(params.get("productId") + "")) ? null : Long.valueOf((String) params.get("productId"));
		pageIndex = params.get("pageIndex") == null ? pageIndex : Integer.parseInt(params.get("pageIndex") + "");
		pageSize = params.get("pageSize") == null ? pageSize : Integer.parseInt(params.get("pageSize") + "");
		return speedloanManager.index(cust, accessToken, appDesc, productId, pageIndex, pageSize);
	}

	@Log
	@RequestMapping("index/v3")
	public JsonResult<SpeedIndexV3Dto> indexV3(@RequestBody Map<String, Object> refreshFields, HttpServletRequest request) throws Exception {

		Cust cust = null;
		String accessToken = request.getHeader("accessToken");
		String appDesc = request.getHeader("appDesc");
		Long custId = null;
		if (super.hasOnLine(request)) {
			custId = appTokenService.getCustIdFromToken(accessToken);
			cust = custManager.findById(custId);
		}

		cust = cust == null ? new Cust() : cust;

		/*
		 * int pageIndex = 0; int pageSize = 20;
		 */
		String refreshFieldss = String.valueOf(refreshFields.get("refreshFields"));
		int pageIndex2 = Integer.parseInt(String.valueOf(refreshFields.get("pageIndex")));
		int pageSize2 = Integer.parseInt(String.valueOf(refreshFields.get("pageSize")));

		return  JsonResult.SuccessResponse(speedloanManager.indexV3(cust, refreshFieldss, accessToken, appDesc, pageIndex2, pageSize2));

	}

	/**
	 * 一键申请
	 * 
	 * @author zhaoqi01
	 * @param paramMap
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("creditPrecheck")
	public SpeedloanPrecheckItemDto creditPrecheck(@RequestBody Map<String, Object> paramMap, HttpServletRequest request) throws Exception {
		SpeedloanPrecheckItemDto result = speedloanManager.creditPrecheck(paramMap, super.getCust(request));
		return result;
	}

	/**
	 * 预检2.0
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("creditPreview")
	public SpeedloanPreviewDto creditPreview(HttpServletRequest request) throws Exception {
		String appDesc = request.getHeader("appDesc");
		Cust cust = custManager.findById(super.getCust(request).getCustId());
		return speedloanManager.speedloanPreview(cust, appDesc);
	}

	/**
	 * 获得可申请产品
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("getCanApplyProducts")
	public SpeedloanCanApplyProductsDto getCanApplyProducts(HttpServletRequest request) throws Exception {
		String appDesc = request.getHeader("appDesc");
		Cust cust = custManager.findById(super.getCust(request).getCustId());
		return speedloanManager.getCanApplyProducts(cust, appDesc);
	}

	/**
	 * 提交审批
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("speedloanCommit")
	public JsonResult speedloanCommit(HttpServletRequest request) throws Exception {
		String appDesc = request.getHeader("appDesc");
		Cust cust = custManager.findById(super.getCust(request).getCustId());
		Map<String, Object> paramMap = new HashMap<>();
		if (request.getHeader("appInfo") != null) {
			paramMap = JacksonUtil.Json2Map(request.getHeader("appInfo"));
		}
		speedloanManager.speedloanCommit(cust, appDesc, paramMap);
		return JsonResult.SuccessResponse(null);
	}

	/**
	 * 热门推荐列表
	 * @param paramMap
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("popularRecommend")
	public JsonResult popularRecommend(@RequestBody Map<String, Object> paramMap,HttpServletRequest request) throws Exception {
		String appDesc = request.getHeader("appDesc");
		String accessToken = request.getHeader("accessToken");
		Cust cust = custManager.findById(super.getCust(request).getCustId());
		List<LoanProductsDto> popularRecommend=speedloanManager.popularRecommend(cust,appDesc,accessToken,paramMap);
		Map<String,List<LoanProductsDto>> result=new HashMap();
		result.put("loanProducts",popularRecommend);
		return JsonResult.SuccessResponse(result);
	}
}
